/**
 * 
 */
package cn.kuaipai.mail.service.impl;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import cn.kuaipai.mail.model.SmtpInfo;
import cn.kuaipai.mail.model.MailInfo;
import cn.kuaipai.mail.service.MailService;

/**
 * @author zy
 */
public class MailServiceImpl implements MailService {
	
	protected final Logger logger_monitor = Logger.getLogger(this.getClass());
	protected final Logger logger_exception = Logger.getLogger(this.getClass());

	private SmtpInfo mailHeader ;
	
	public void setMailHeader(SmtpInfo mailHeader) {
		this.mailHeader = mailHeader;
	}

	@Override
	public boolean sendMail(MailInfo mailInfo) {
		logger_monitor.info("[Mail] sendMail " + mailInfo.toString());
		Properties props = new Properties();
		props.put("mail.smtp.host", mailHeader.getSmtp());
		props.put("mail.smtp.auth", "true");
		try {
			Session mailSession = Session.getDefaultInstance(props);
			mailSession.setDebug(true);
			Message message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(mailInfo.getFrom()));
			Address[] tos = new Address[mailInfo.getTos().length];
			for (int i = 0; i < mailInfo.getTos().length; i++) {
				tos[i] = new InternetAddress(mailInfo.getTos()[i]);
			}
			message.addRecipients(Message.RecipientType.TO, tos);

			if (mailInfo.getCcs() != null && mailInfo.getCcs().length > 0) {
				Address[] ccs = new Address[mailInfo.getCcs().length];
				for (int i = 0; i < mailInfo.getCcs().length; i++) {
					ccs[i] = new InternetAddress(mailInfo.getCcs()[i]);
				}
				message.addRecipients(Message.RecipientType.CC, ccs);
			}

			if (mailInfo.getBccs() != null && mailInfo.getBccs().length > 0) {
				Address[] bccs = new Address[mailInfo.getBccs().length];
				for (int i = 0; i < mailInfo.getBccs().length; i++) {
					bccs[i] = new InternetAddress(mailInfo.getBccs()[i]);
				}
				message.addRecipients(Message.RecipientType.BCC, bccs);
			}

			message.setSubject(mailInfo.getSubject());
			message.setContent(mailInfo.getContent(),"text/html;charset=utf-8");
			message.setSentDate(new Date());
			message.setHeader("X-Priority", String.valueOf(mailInfo.getPriority()));
			message.saveChanges();
			Transport transport = mailSession.getTransport("smtp");
			// 连接SMTP服务器
			transport.connect(mailHeader.getSmtp(), mailHeader.getUsername(),mailHeader.getPassword());
			// 发送邮件
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			logger_monitor.info("[Mail] sendMail " + mailInfo.toString() + " OK ");
			return true ;
		} catch (Exception e) {
			logger_exception.error("[mail] sendMail error !", e);
			return false ;
		}
	}

}
